import logging
import queue
import threading
from logging.handlers import QueueHandler, QueueListener

def setup_async_logging(config):
    """设置异步日志处理"""
    # 创建队列
    log_queue = queue.Queue(-1)  # 无限队列
    
    # 创建队列处理器
    queue_handler = QueueHandler(log_queue)
    
    # 配置根日志记录器使用队列处理器
    root = logging.getLogger()
    root.addHandler(queue_handler)
    root.setLevel(logging.INFO)
    
    # 从配置中创建实际的处理器
    handlers = []
    for handler_config in config['handlers'].values():
        handler_class = eval(handler_config['class'])
        handler = handler_class(**{k: v for k, v in handler_config.items() if k != 'class'})
        handlers.append(handler)
    
    # 创建并启动队列监听器
    listener = QueueListener(log_queue, *handlers, respect_handler_level=True)
    listener.start()
    
    return listener  # 返回监听器以便后续停止